package atom.core0.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import atom.core0.exception.BizSysException;

public class IPUtil
{
	public static void main(String[] args) throws Exception
	{
		InetAddress ia = InetAddress.getLocalHost();
		System.out.println(ia.getCanonicalHostName());
		System.out.println(ia);

	}

	public static void printLocalIPs() throws BizSysException
	{
		// InetAddress ia = InetAddress.getLocalHost();

		// System.out.println(ia.getHostAddress());

		// 获得多个网卡的IP地址
		// 在window下面可以工作。在Linux下返回127.0.0.1。主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址，而不是网卡的绑定地址。后来改用网卡的绑定地址，可以取到本机的ip地址：）

		try
		{
			// abc123为你的主机名称
			String hostName;
			hostName = InetAddress.getLocalHost().getHostName();
			System.out.println(hostName);
			InetAddress hosts[] = InetAddress.getAllByName(hostName);
			for (int i = 0; i < hosts.length; i++)
			{
				// 比较你的外网IP网段判断
				System.out.println(hosts[i].getHostAddress());
			}
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}

	}

	public static String getLocalIPV4() throws BizSysException
	{
		String localIP = "";
		// InetAddress ia = InetAddress.getLocalHost();
		try
		{
			Enumeration<NetworkInterface> netInterfaces = null;
			try
			{
				netInterfaces = NetworkInterface.getNetworkInterfaces();
				while (netInterfaces.hasMoreElements())
				{
					NetworkInterface ni = netInterfaces.nextElement();
					Enumeration<InetAddress> ips = ni.getInetAddresses();
					while (ips.hasMoreElements())
					{
						localIP = ips.nextElement().getHostAddress();
						// IP V6的地址含有:
						if (localIP.length() > 15)
							continue;
						if (localIP.indexOf(":") != -1)
							continue;

						// local地址
						if (localIP.equals("127.0.0.1"))
							continue;
						break;
					}
					// IP V6的地址
					if (localIP.length() > 15)
						continue;
					// local地址
					if (localIP.equals("127.0.0.1"))
						continue;

					break;

				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			/*
			 * String hostName; hostName =
			 * InetAddress.getLocalHost().getHostName(); InetAddress hosts[] =
			 * InetAddress.getAllByName(hostName); for (int i = 0; i <
			 * hosts.length; i++) { // 比较你的外网IP网段判断 localIP =
			 * hosts[i].getHostAddress(); //IP V6的地址 if (localIP.length()>15)
			 * continue; //local地址 if (localIP.equals("127.0.0.1")) continue;
			 * 
			 * break; }
			 */
		}
		catch (Exception e)
		{
			throw new BizSysException("获得本地IP地址异常");
		}
		return localIP;
	}

}
